package com.zhangxx.web.common.aspect;

import com.zhangxx.web.common.annotation.Authentication;
import com.zhangxx.web.common.exception.IllegalRequestException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**      
 * @Description:全局权限验证功能

 */
@Aspect
@Component
@Order(10)
public class AuthenticationAspect {

	/**
	 * 定义日志切点
	 */
	@Pointcut("@annotation(com.zhangxx.web.common.annotation.Authentication)")
	public void controllerAspect() {
	}

	/**
	 * 配置环绕通知,使用在方法aspect()上注册的切入点，环绕通知包含了另外四中通知的功能，因此不建议同时使用
	 * 
	 * @param joinPoint
	 * @throws Throwable
	 */
	
	 @Around("controllerAspect()")
	 public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();//获取request
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature)signature;
		Method method = methodSignature.getMethod();
		Authentication authSettings = method.getAnnotation(Authentication.class);
		 if (authSettings.required()) {
			 String token = request.getHeader("token");
			 if(!"5245@#*&G_(&".equals(token)){
				 throw new IllegalRequestException("非法访问");
			 }
		 }
		Object[] args = joinPoint.getArgs();
		return joinPoint.proceed(args);
	 }

}
